<?php

/**
 * @copyright: ©2024 永州微聚商 网络科技有限公司
 * @link: https://www.weiJuyunke.com
 */

namespace app\mobile\controller;

use app\admin\model\FigureDistribution;
use app\BaseController;
use app\common\service\ApiService;
use think\facade\Db;
use think\Model;
use app\admin\model\FigureSystem;
use app\admin\model\FigureUser;
use app\admin\model\FigureAvatar;
use app\admin\model\FigureBrokerageSet;
use app\admin\model\FigureBrokerageLog;
use app\admin\model\FigurePointLog;
use app\admin\model\FigureUserSet;
use app\admin\model\FigurePointSet;
use app\admin\model\FigurePartner;
use app\admin\model\FigureBalanceLog;
use app\admin\model\FigureMemberLog;
use app\admin\model\template\BrokerageArrival;

/**
 * 用户操作
 *
 * @author Administrator
 *
 */
class User extends BaseController
{

    /**
     * 用户设置
     * http://aigc.weijuyunke.cn/mobile/user/set
     */
    public function set()
    {
        $set = FigureUserSet::where("id", 1)->find();

        if (empty($set)) {
            $set = [];
        }

        return result(0, 'success', $set);
    }

    /**
     * 获取openid
     * http://aigc.weijuyunke.cn/mobile/user/getOpenId
     *
     * @param
     *            code
     */
    public function getOpenId()
    {
        $system = FigureSystem::where("id", 1)->find();
        if (empty($system)) {
            return result(-1, '平台配置为空');
        }

        $code = input('code');
        if (empty($code)) {
            return result(-1, 'code为空');
        }

        $appid = $system['appid'];
        $secret = $system['appsecret'];

        $api = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $appid . "&secret=" . $secret . "&js_code=" . $code . "&grant_type=authorization_code";
        $info = httpGet($api); // get请求网址，获取数据

        $json = json_decode($info); // 对json数据解码
        $arr = get_object_vars($json); // 返回一个数组。获取$json对象中的属性，组成一个数组

        if (!empty($arr['errcode'])) {
            return result(-1, $arr['errmsg']);
        } else {
            $openid = $arr['openid'];
            $unionid = empty($arr['unionid']) ? '' : $arr['unionid'];
            $session_key = $arr['session_key'];
            if (empty($openid)) {
                return result(-1, 'fail');
            } else {
                return result(0, 'success', $arr);
            }
        }
    }

    /**
     * 获取微信授权手机号码
     * http://aigc.weijuyunke.cn/mobile/user/getTelphone
     *
     * @param
     *            code
     */
    public function getTelphone()
    {
        $system = FigureSystem::where("id", 1)->find();
        if (empty($system)) {
            return result(-1, '平台配置为空');
        }

        $code = input('code');
        if (empty($code)) {
            return result(-1, 'code为空');
        }

        $appid = $system['appid'];
        $secret = $system['appsecret'];

        $api = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $secret;

        $info = httpGet($api); // get请求网址，获取数据
        $arr_access_token = json_decode($info, true); // 对json数据解码

        if (!$arr_access_token) {
            return result(-1, '请求异常');
        }

        $access_token = $arr_access_token['access_token'];
        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" . $access_token;
        $send_data = array(
            'code' => $code
        );
        $data = json_encode($send_data);
        $phone = json_decode(wtw_request($url, $data));

        return result(0, 'success', $phone);
    }

    /**
     * 敏感词校验
     * http://aigc.weijuyunke.cn/mobile/user/msgSecCheck
     *
     * @param
     *            openid
     * @param
     *            content 内容
     * @param
     *            scene 1 资料；2 评论；3 论坛；4 社交日志
     * @param
     *            nickname 用户昵称
     */
    public function msgSecCheck()
    {
        $system = FigureSystem::where("id", 1)->find();
        if (empty($system)) {
            return result(-1, '平台配置为空');
        }

        $content = input('content');
        if (empty($content)) {
            return result(-1, 'content为空');
        }

        $content = mb_convert_encoding($content, "UTF-8", "auto");

        $appid = $system['appid'];
        $secret = $system['appsecret'];

        $api = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $secret;

        $info = httpGet($api); // get请求网址，获取数据
        $arr_access_token = json_decode($info, true); // 对json数据解码

        if (!$arr_access_token) {
            return result(-1, '请求异常');
        }

        $access_token = $arr_access_token['access_token'];
        $url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=" . $access_token;
        $send_data = array(
            'content' => $content,
            'version' => 2,
            'scene' => input('scene'),
            'openid' => input('openid')
        );

        if (!empty(input('nickname'))) {
            $send_data['nickname'] = mb_convert_encoding(input('nickname'), "UTF-8", "auto");
        }

        $data = json_encode($send_data);
        $result = json_decode(wtw_request($url, $data));

        return result(0, 'success', $result);
    }

    /**
     * 用户授权
     * http://aigc.weijuyunke.cn/mobile/user/register
     *
     * @param
     *            pid
     * @param
     *            openid
     * @param
     *            unionid
     * @param
     *            avatar 头像
     * @param
     *            nickname 昵称
     * @param
     *            telphone 手机号码
     */
    public function register()
    {
        $request = $this->request;
        $domain = $request->domain();

        $openid = input('openid');

        if (empty($openid)) {
            return result(-1, 'openid为空');
        }

        if (!preg_match('/^[_A-Za-z0-9\-]{10,40}$/', $openid)) {
            return result(-1, '非法的openid');
        }

        $data = array(
            'openid' => $openid
        );

        if (!empty(input('avatar'))) {
            $data['avatar'] = input('avatar');
        } else {
            $data['avatar'] = $domain . "/imgs/def_user.png";
        }

        if (!empty(input('nickname'))) {
            $data['nickname'] = input('nickname');
        } else {
            $data['nickname'] = '用户' . substr(input('telphone'), -4);
        }

        if (!empty(input('unionid'))) {
            $data['unionid'] = input('unionid');
        }
        if (!empty(input('telphone'))) {
            if (!preg_match("/^1[3456789]\d{9}$/", input('telphone'))) {
                return result(-1, '非法的手机号码');
            }


            if (strlen(input('telphone') )> 11){
                return result(-1, '手机号有误');
            }
            $apiService = new ApiService();
            $apiService->interfaceTest(input('telphone'));
            $data['telphone'] = input('telphone');
        }



        $res = FigureUser::where([
            'telphone' => input('telphone')
        ])->find();

        if (!$res) {
            $FigureDistributionModel = new FigureDistribution();
            $FigureDistributionInfo = $FigureDistributionModel->where(['level' => 1])->find();
            if ($FigureDistributionInfo) {
                $data['distribution_level'] = 1;
                $data['distribution_level_id'] = $FigureDistributionInfo['id'];

            }
            $user = new FigureUser();
            $user->save($data);
            $uid = $user->id;

            $pid = 0;
            if (!empty(input('pid'))) {
                $pid = input('pid');
            }

            $set = FigureBrokerageSet::where("id", 1)->find();

            if (!empty($pid) /*&& ! empty($set['invite'])*/) {

                $pUser = FigureUser::where('id', $pid)->find();
                if ($pUser) {

                    $user = FigureUser::where([
                        'openid' => $openid
                    ])->find();

                    if ($set['invite'] > 0) {
                        $log = new FigureBrokerageLog();
                        $log->save([
                            'type' => 1,
                            'pid' => $pid,
                            'uid' => $user['id'],
                            'money' => $set['invite'],
                            'is_repurchase' => 2,
                        ]);

                        $pUser->save([
                            'brokerage' => Db::raw('brokerage+' . $set['invite'])
                        ]);
                    }


                    // 模板消息不用佣金到账的
                    /*     $brokerageArrival = new BrokerageArrival([
                             'openid' => $pUser['openid'],
                             'pname' => $pUser['nickname'],
                             'uname' => $data['nickname'],
                             'name' => '邀请入驻',
                             'money' => 0,
                             'brokerage' => $set['invite']
                         ]);
                         $brokerageArrival->send();*/

                    $user->save([
                        'pid' => $pid
                    ]);
                }
            }

            return result(0, 'success', $uid);
        } else {
            $uid = $res['id'];

            if (empty($res['qrcode'])) {
                $url = "pages/index/index";
                $userUrl = qr_code($uid, $url, 'user');
                $data['qrcode'] = $userUrl;
            }

            $res->save($data);
            return result(0, 'success', $uid);
        }
    }

    /**
     * 新人领取
     * http://aigc.weijuyunke.cn/mobile/user/newGet
     *
     * @param
     *            uid
     */
    public function newGet()
    {
        try {
            $uid = input('uid');
            if (empty($uid)) {
                return result(1, 'uid为空');
            }

            $user = FigureUser::where('id', $uid)->find();

            if (empty($user)) {
                return result(-1, '未找到用户');
            }

            $joinDay = (time() - strtotime($user['create_time'])) / 86400;
            if ($joinDay > 3) {
                return result(-1, '非新人，不可领取');
            }

            $newLog = FigureBalanceLog::where([
                'uid' => $uid,
                'way' => 2
            ])->find();

            if (!empty($newLog)) {
                return result(1, '不可重复领取');
            }

            $userSet = FigureUserSet::where("id", 1)->find();

            if (!isset($userSet) || $userSet['new_open'] != 1) {
                return result(-1, '未开启，不可领取');
            }

            if (!empty($userSet['new_get']) && $userSet['new_get'] > 0) {

                $log_no = getPayNo('NEW');

                $log = new FigureBalanceLog();
                $log->save([
                    'uid' => $uid,
                    'log_no' => $log_no,
                    'type' => 1,
                    'way' => 2,
                    'current' => $user['balance'],
                    'money' => $userSet['new_get'],
                    'desc' => '新人赠送'
                ]);

                $user->save([
                    'balance' => Db::raw('balance+' . $userSet['new_get'])
                ]);
            }

            return result(0, '领取成功');
        } catch (\Exception $e) {
            return result(-1, '异常' . $e->getMessage());
            exit();
        }
    }

    /**
     * 用户信息
     * http://aigc.weijuyunke.cn/mobile/user/userInfo
     *
     * @param
     *            uid
     */
    public function userInfo()
    {
        try {
            $request = $this->request;
            $user_id = $this->request->_UID;

            $uid = input('uid');
            if (empty($uid)) {
                return result(1, 'uid为空');
            }

            $user = FigureUser::where('id', $uid)->find();

            if (empty($user)) {
                return result(-1, '未找到用户');
            }

            if (empty($user['qrcode'])) {
                $url = "pages/index/index";
                $userUrl = qr_code($uid, $url, 'user');
                $user->save([
                    'qrcode' => $userUrl
                ]);
            }

            $is_new = 0;

            $userSet = FigureUserSet::where("id", 1)->find();
            if (isset($userSet) && $userSet['new_open'] == 1) {
                $joinDay = (time() - strtotime($user['create_time'])) / 86400;
                if ($joinDay <= 3) {

                    $newLog = FigureBalanceLog::where([
                        'uid' => $uid,
                        'way' => 2
                    ])->find();

                    if (empty($newLog)) {
                        $is_new = 1;
                    }
                }
            }

            $user['is_new'] = $is_new;

            $avatar_count = FigureAvatar::where("uid = {$uid} AND current_status = 'completed'")->count();
            $user['avatar_count'] = empty($avatar_count) ? 0 : $avatar_count;

            $partner = FigurePartner::where('uid', $uid)->find();

            if (empty($partner)) {
                $user['partner_status'] = 0;
                $user['partner_id'] = 0;
                $user['partner_freeze'] = -1;
                $user['partner_name'] = '';
                $user['partner_telphone'] = '';
                $user['partner_refuse'] = '';
            } else {
                $user['partner_status'] = $partner['is_status'];
                $user['partner_id'] = $partner['id'];
                $user['partner_freeze'] = $partner['is_freeze'];
                $user['partner_name'] = $partner['name'];
                $user['partner_telphone'] = $partner['telphone'];
                $user['partner_refuse'] = $partner['refuse'];
            }
            $FigureDistribution = new FigureDistribution();
            $FigureDistributionInfo = $FigureDistribution->where(['id' => $user['distribution_level_id']])->find();
            if ($FigureDistributionInfo['is_shareholder_swich'] == 1) {
                $user['is_shareholder'] = 1;
            } else {
                $user['is_shareholder'] = 0;
            }

            return result(0, '用户信息', $user);
        } catch (\Exception $e) {
            return result(-1, '异常' . $e->getMessage());
            exit();
        }
    }

    /**
     * 设置手机号码
     * https://aigc.weijuyunke.cn/mobile/user/updatePhone
     *
     * @param
     *            uid
     * @param
     *            telphone
     */
    public function updatePhone()
    {
        $uid = input('uid');
        $telphone = input('telphone');
        if (empty($uid)) {
            return result(1, 'uid为空');
        }

        if (empty($telphone)) {
            return result(1, '手机号码为空');
        }

        if (!preg_match("/^1[3456789]\d{9}$/", $telphone)) {
            return result(-1, '非法的手机号码');
        }

        $user = FigureUser::where('id', $uid)->find();

        if (empty($user)) {
            return result(-1, '未找到用户');
        }

        $user->save([
            'telphone' => $telphone
        ]);

        return result(0, '设置成功');
    }

    /**
     * 余额记录
     * https://aigc.weijuyunke.cn/mobile/user/balanceLog
     *
     * @param
     *            uid
     * @param
     *            type 1-收入 2-支出
     * @param
     *            b_type 1-点数 2-次数
     * @param
     *            way 0-后台 1-充值 2-新人赠送 3-声音克隆 4-形象克隆 5-视频换脸 6-视频剪辑 7-会员 8-ai创作
     * @param
     *            page 页码
     * @param
     *            psize 每页条数
     */
    public function balanceLog()
{
    $pindex = max(1, intval(input('page')));
    $psize = empty(input('psize')) ? 10 : intval(input('psize'));

    $uid = input('uid');

    $where = " uid = {$uid}";

    if (!empty(input('type'))) {
        if (input('type') ==1){
            $where .= " AND (type =   1 or type = 3)";
        }else{
            $where .= " AND type =  2";
        }

    }

    //  1 形象

    if ( input('way') != '') {
        $way = input('way');
        if ($way == 6) {
            $where .= " AND way in (6,10,13，28)";
        } elseif ($way == 4) {
            $where .= " AND way in (4)";
        } elseif ($way == 3) {
            $where .= " AND way in (3,15)";
        } elseif ($way == 14) {
            $where .= " AND way in (14,16)";
        } elseif ($way == 18) {
            $where .= " AND way in (22,24,26)";
        }
        elseif ($way == 19) {
            $where .= " AND way in (23,25,27)";
        }
        elseif ($way == 20) {
            $where .= " AND way in (18,19,20,21)";
        }  elseif ($way == 31) {
            $where .= " AND way in (31,32)";
        } elseif ($way == 40) {
            $where .= " AND way in (50,33,34,35,36,37,38,39,51,52)";
        }

        else {
            $where .= " AND way = " . input('way');
        }
    }

    if (!empty(input('b_type'))) {
        $where .= " AND b_type = " . input('b_type');
    }

    $FigureBalanceLog = new FigureBalanceLog();
    $total = $FigureBalanceLog->where($where)->count();



    if ($total) {

        $list = FigureBalanceLog::where($where)->order("create_time", "DESC")
            ->limit(($pindex - 1) * $psize, $psize)
            ->select();
        foreach ($list as $key => $value ){
            if ($value['type']  ==3){
                $list[$key]['type'] =1;
            }
            if (in_array($value['way'],[50,33,34,35,36,37,38,39,51,52])){
                $list[$key]['way'] = 40;
            }


        }

    } else {
        $list = array();
    }

    $totalPage = ceil($total / $psize);

    return result(0, 'success', array(
        'list' => $list,
        'total' => $total,
        'pindex' => $pindex,
        'psize' => $psize,
        'totalPage' => $totalPage
    ));
}
}